<template>
  <div class="order-detail-container">
    <NavBar>
      <template #default>订单详情</template>
    </NavBar>

    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>

    <div v-else-if="error" class="error-container">
      <el-icon class="error-icon"><WarningFilled /></el-icon>
      <p class="error-message">{{ error }}</p>
      <el-button @click="fetchOrderDetail" type="primary">重新加载</el-button>
    </div>

    <div v-else-if="orderDetail" class="order-detail-content">
      <!-- 订单状态卡片 -->
      <div class="status-section">
        <div class="status-icon" :class="getStatusIconClass(orderDetail.orderStatus)">
          <component :is="getStatusIcon(orderDetail.orderStatus)" />
        </div>
        <div class="status-info">
          <div class="status-text" :class="getOrderStatusColor(orderDetail.orderStatus)">
            {{ getOrderStatusText(orderDetail.orderStatus) }}
          </div>
          <div class="status-desc">{{ getStatusDescription(orderDetail.orderStatus) }}</div>
        </div>
      </div>

      <!-- 物流信息 (仅在已发货状态显示) -->
      <div v-if="orderDetail.orderStatus >= ORDER_STATUS.SHIPPED" class="logistics-section">
        <div class="section-title">
          <el-icon><Van /></el-icon>
          <span>物流信息</span>
        </div>
        <div class="logistics-info">
          <div class="tracking-number">订单已发货</div>
          <div class="logistics-company">正在配送中，请耐心等待</div>
        </div>
        <div class="logistics-status" v-if="orderDetail.shippingTime">
          <div class="logistics-item">
            <div class="logistics-time">{{ formatDateTime(orderDetail.shippingTime) }}</div>
            <div class="logistics-desc">商品已发货</div>
          </div>
        </div>
      </div>

      <!-- 收货地址信息 -->
      <div class="address-section">
        <div class="section-title">
          <el-icon><Location /></el-icon>
          <span>收货信息</span>
        </div>
        <div class="address-info">
          <div v-if="orderDetail.addressInfo" class="address-details">
            <div class="address-line1">
              <span class="recipient">{{ orderDetail.addressInfo.receiverName }}</span>
              <span class="phone">{{ orderDetail.addressInfo.receiverMobile }}</span>
            </div>
            <div class="address-line2">
              {{ orderDetail.addressInfo.province }}{{ orderDetail.addressInfo.city }}{{ orderDetail.addressInfo.district }}{{ orderDetail.addressInfo.detailAddress }}
            </div>
          </div>
          <div v-else class="address-fallback">
            <div class="address-line1">
              <span class="recipient">收货地址ID: {{ orderDetail.addressId }}</span>
            </div>
            <div class="address-line2">
              <span class="address-note">地址信息加载失败，请联系客服</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="goods-section">
        <div class="section-title">
          <el-icon><Goods /></el-icon>
          <span>商品信息</span>
        </div>
        <div class="goods-list">
          <div
            v-for="item in orderDetail.orderItems"
            :key="item.orderItemId"
            class="goods-item"
            @click="goToProductDetail(item.productId)"
          >
            <img :src="formatImageUrl(item.mainImage)" :alt="item.productName" class="goods-image" />
            <div class="goods-info">
              <h4 class="goods-name">{{ item.productName }}</h4>
              <div class="goods-spec" v-if="item.productSpec">规格：{{ item.productSpec }}</div>
              <div class="goods-price-quantity">
                <span class="goods-price">￥{{ formatPrice(item.price) }}</span>
                <span class="goods-quantity">x{{ item.quantity }}</span>
              </div>
            </div>
            <div class="goods-total">
              ￥{{ formatPrice(item.price * item.quantity) }}
            </div>
          </div>
        </div>

        <!-- 价格明细 -->
        <div class="price-detail">
          <div class="price-item">
            <span class="price-label">商品数量</span>
            <span class="price-value">{{ orderDetail.totalQuantity || '未知' }}件</span>
          </div>
          <div class="price-item total">
            <span class="price-label">订单总额</span>
            <span class="price-value total">￥{{ formatPrice(orderDetail.totalAmount) }}</span>
          </div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="order-info-section">
        <div class="section-title">
          <el-icon><Document /></el-icon>
          <span>订单信息</span>
        </div>
        <div class="order-info-list">
          <div class="info-item">
            <span class="info-label">订单编号</span>
            <span class="info-value">{{ orderDetail.orderId }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">最后更新</span>
            <span class="info-value">{{ formatDateTime(orderDetail.updateTime) }}</span>
          </div>
          <div class="info-item" v-if="orderDetail.paymentTime">
            <span class="info-label">付款时间</span>
            <span class="info-value">{{ formatDateTime(orderDetail.paymentTime) }}</span>
          </div>
          <div class="info-item" v-if="orderDetail.shippingTime">
            <span class="info-label">发货时间</span>
            <span class="info-value">{{ formatDateTime(orderDetail.shippingTime) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">支付方式</span>
            <span class="info-value">{{ getPaymentMethodText(orderDetail.paymentType) }}</span>
          </div>
          <div class="info-item" v-if="orderDetail.remark">
            <span class="info-label">订单备注</span>
            <span class="info-value">{{ orderDetail.remark }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div v-if="orderDetail && !loading" class="bottom-actions">
      <div class="action-buttons">
        <!-- 待支付状态 -->
        <template v-if="orderDetail.orderStatus === ORDER_STATUS.PENDING_PAYMENT">
          <el-button @click="cancelOrder" :loading="isOperating">取消订单</el-button>
          <el-button @click="payOrder" type="primary" :loading="isOperating">立即支付</el-button>
        </template>

        <!-- 待发货状态 -->
        <template v-else-if="orderDetail.orderStatus === ORDER_STATUS.PAID_PENDING_SHIP">
          <el-button @click="applyRefund" :loading="isOperating">申请退款</el-button>
        </template>

        <!-- 已发货状态 -->
        <template v-else-if="orderDetail.orderStatus === ORDER_STATUS.SHIPPED">
          <el-button @click="checkLogistics">查看物流</el-button>
          <el-button @click="confirmReceipt" type="primary" :loading="isOperating">确认收货</el-button>
        </template>

        <!-- 已完成状态 -->
        <template v-else-if="orderDetail.orderStatus === ORDER_STATUS.COMPLETED">
          <el-button @click="goToReview">去评价</el-button>
          <el-button @click="buyAgain" type="primary">再次购买</el-button>
        </template>

        <!-- 通用操作 -->
        <el-button v-if="showContactService" @click="contactService">联系客服</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Loading,
  WarningFilled,
  Location,
  Goods,
  Document,
  Van,
  CircleCheckFilled,
  Clock,
  Truck,
  CircleCloseFilled
} from '@element-plus/icons-vue';
import NavBar from '../../components/common/NavBar.vue';
import {
  getOrderDetailAPI,
  cancelOrderAPI,
  confirmReceiptAPI,
  applyRefundAPI,
  ORDER_STATUS,
  getOrderStatusText,
  getOrderStatusColor
} from '@/api/OrderApi';

const route = useRoute();
const router = useRouter();

// 响应式数据
const orderDetail = ref(null);
const loading = ref(false);
const error = ref(null);
const isOperating = ref(false);

// 计算属性
const showContactService = computed(() => {
  return orderDetail.value && [
    ORDER_STATUS.AFTER_SALE,
    ORDER_STATUS.REFUNDED
  ].includes(orderDetail.value.orderStatus);
});

// 获取订单详情
const fetchOrderDetail = async () => {
  const orderId = route.params.orderId;
  if (!orderId) {
    error.value = '订单ID参数缺失';
    return;
  }

  loading.value = true;
  error.value = null;

  try {
    const response = await getOrderDetailAPI(orderId);

    if (response.data.code === 1) {
      const { addressDTO, ordersDTO } = response.data.data;

      // 合并addressDTO和ordersDTO，保持原有的数据结构
      orderDetail.value = {
        // 订单信息来自ordersDTO
        ...ordersDTO,
        // 地址信息来自addressDTO
        addressInfo: addressDTO,
        // 保持向后兼容，也可以通过addressId访问
        addressId: ordersDTO.addressId
      };

      console.log('订单详情获取成功:', orderDetail.value);
    } else {
      throw new Error(response.data.msg || '获取订单详情失败');
    }
  } catch (err) {
    console.error('获取订单详情失败:', err);
    error.value = err.message || '获取订单详情失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatDateTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化图片URL
const formatImageUrl = (url) => {
  if (!url) return '';
  return url.replace(/\\/g, '/');
};

// 格式化价格
const formatPrice = (price) => {
  if (!price && price !== 0) return '0.00';
  return Number(price).toFixed(2);
};

// 获取支付方式文本
const getPaymentMethodText = (paymentType) => {
  const methods = {
    1: '支付宝',
    2: '微信支付',
    3: '银行卡'
  };
  return methods[paymentType] || '未知支付方式';
};

// 获取订单状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    [ORDER_STATUS.PENDING_PAYMENT]: Clock,
    [ORDER_STATUS.PAID_PENDING_SHIP]: CircleCheckFilled,
    [ORDER_STATUS.SHIPPED]: Truck,
    [ORDER_STATUS.RECEIVED]: CircleCheckFilled,
    [ORDER_STATUS.COMPLETED]: CircleCheckFilled,
    [ORDER_STATUS.CANCELLED]: CircleCloseFilled,
    [ORDER_STATUS.REFUNDED]: CircleCloseFilled
  };
  return iconMap[status] || Clock;
};

// 获取状态图标样式类
const getStatusIconClass = (status) => {
  const classMap = {
    [ORDER_STATUS.PENDING_PAYMENT]: 'status-pending',
    [ORDER_STATUS.PAID_PENDING_SHIP]: 'status-paid',
    [ORDER_STATUS.SHIPPED]: 'status-shipped',
    [ORDER_STATUS.RECEIVED]: 'status-received',
    [ORDER_STATUS.COMPLETED]: 'status-completed',
    [ORDER_STATUS.CANCELLED]: 'status-cancelled',
    [ORDER_STATUS.REFUNDED]: 'status-refunded'
  };
  return classMap[status] || 'status-default';
};

// 获取状态描述
const getStatusDescription = (status) => {
  const descMap = {
    [ORDER_STATUS.PENDING_PAYMENT]: '请在24小时内完成支付',
    [ORDER_STATUS.PAID_PENDING_SHIP]: '商家正在为您准备商品',
    [ORDER_STATUS.SHIPPED]: '商品正在配送中，请耐心等待',
    [ORDER_STATUS.RECEIVED]: '商品已送达，感谢您的购买',
    [ORDER_STATUS.COMPLETED]: '交易已完成，感谢您的购买',
    [ORDER_STATUS.CANCELLED]: '订单已取消',
    [ORDER_STATUS.REFUNDED]: '订单已退款'
  };
  return descMap[status] || '';
};

// 取消订单
const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个订单吗？取消后无法恢复。',
      '取消订单',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '我再想想',
        type: 'warning'
      }
    );

    isOperating.value = true;
    const response = await cancelOrderAPI(orderDetail.value.orderId);
    if (response.data.code === 1) {
      ElMessage.success('订单已取消');
      fetchOrderDetail(); // 刷新订单详情
    } else {
      throw new Error(response.data.msg || '取消订单失败');
    }
  } catch (error) {
    if (error !== 'cancel') { // 用户点击取消时不显示错误
      console.error('取消订单失败:', error);
      ElMessage.error(error.message || '取消订单失败');
    }
  } finally {
    isOperating.value = false;
  }
};

// 去支付
const payOrder = () => {
  router.push({
    path: '/payment',
    query: {
      orderId: orderDetail.value.orderId,
      amount: orderDetail.value.totalAmount,
      paymentType: orderDetail.value.paymentType
    }
  });
};

// 申请退款
const applyRefund = async () => {
  try {
    const { value } = await ElMessageBox.prompt(
      '请填写退款原因',
      '申请退款',
      {
        confirmButtonText: '提交申请',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入退款原因',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '请填写退款原因';
          }
          return true;
        }
      }
    );

    isOperating.value = true;
    const response = await applyRefundAPI(orderDetail.value.orderId, {
      reason: value.trim(),
      description: value.trim()
    });

    if (response.data.code === 1) {
      ElMessage.success('退款申请已提交，请等待处理');
      fetchOrderDetail(); // 刷新订单详情
    } else {
      throw new Error(response.data.msg || '申请退款失败');
    }
  } catch (error) {
    if (error !== 'cancel') { // 用户点击取消时不显示错误
      console.error('申请退款失败:', error);
      ElMessage.error(error.message || '申请退款失败');
    }
  } finally {
    isOperating.value = false;
  }
};

// 确认收货
const confirmReceipt = async () => {
  try {
    await ElMessageBox.confirm(
      '确认已收到商品吗？确认后订单将完成。',
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'info'
      }
    );

    isOperating.value = true;
    const response = await confirmReceiptAPI(orderDetail.value.orderId);
    if (response.data.code === 1) {
      ElMessage.success('确认收货成功');
      fetchOrderDetail(); // 刷新订单详情
    } else {
      throw new Error(response.data.msg || '确认收货失败');
    }
  } catch (error) {
    if (error !== 'cancel') { // 用户点击取消时不显示错误
      console.error('确认收货失败:', error);
      ElMessage.error(error.message || '确认收货失败');
    }
  } finally {
    isOperating.value = false;
  }
};

// 查看物流
const checkLogistics = () => {
  ElMessage.info('查看物流功能开发中');
  // 这里可以跳转到物流详情页面或弹出物流信息
};

// 去评价
const goToReview = () => {
  ElMessage.info('评价功能开发中');
  // router.push(`/order/review/${orderDetail.value.orderId}`);
};

// 再次购买
const buyAgain = () => {
  ElMessage.info('再次购买功能开发中');
  // 这里可以将商品加入购物车并跳转
};

// 联系客服
const contactService = () => {
  router.push('/customerService');
};

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push({
    path: '/detail',
    query: { productId }
  });
};

// 组件挂载时获取订单详情
onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped>
.order-detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 44px; /* NavBar高度 */
  padding-bottom: 100px; /* 底部操作栏高度 */
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-container .el-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

/* 错误状态 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #f56c6c;
}

.error-message {
  margin-bottom: 16px;
  text-align: center;
  line-height: 1.4;
}

/* 订单详情内容 */
.order-detail-content {
  padding: 0 16px;
}

/* 通用section样式 */
.status-section,
.logistics-section,
.address-section,
.goods-section,
.order-info-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.section-title .el-icon {
  margin-right: 8px;
  color: #ff5000;
}

/* 订单状态区域 */
.status-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.status-icon.status-pending { background: #ff5000; }
.status-icon.status-paid { background: #1890ff; }
.status-icon.status-shipped { background: #52c41a; }
.status-icon.status-received { background: #722ed1; }
.status-icon.status-completed { background: #722ed1; }
.status-icon.status-cancelled { background: #999; }
.status-icon.status-refunded { background: #fa541c; }

.status-info {
  flex: 1;
}

.status-text {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.status-desc {
  font-size: 14px;
  color: #666;
}

/* 物流信息 */
.logistics-info {
  margin-bottom: 12px;
}

.tracking-number {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.logistics-company {
  font-size: 14px;
  color: #666;
}

.logistics-status {
  border-left: 2px solid #ff5000;
  padding-left: 12px;
}

.logistics-item {
  margin-bottom: 8px;
}

.logistics-time {
  font-size: 12px;
  color: #999;
}

.logistics-desc {
  font-size: 14px;
  color: #333;
  margin-top: 2px;
}

/* 地址信息 */
.address-info {
  line-height: 1.6;
}

.address-line1 {
  margin-bottom: 4px;
}

.recipient {
  font-weight: bold;
  margin-right: 12px;
}

.phone {
  color: #666;
}

.address-line2 {
  color: #666;
  font-size: 14px;
}

.address-note {
  color: #999;
  font-size: 12px;
  font-style: italic;
}

/* 地址加载失败时的样式 */
.address-fallback .address-note {
  color: #ff4757;
  font-size: 12px;
}

/* 商品信息 */
.goods-list {
  margin-bottom: 16px;
}

.goods-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.goods-item:hover {
  background-color: #f8f8f8;
  border-radius: 8px;
  margin: 0 -8px;
  padding: 12px 8px;
}

.goods-item:not(:last-child) {
  border-bottom: 1px solid #f0f0f0;
}

.goods-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  flex-shrink: 0;
}

.goods-info {
  flex: 1;
  min-width: 0;
}

.goods-name {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
}

.goods-spec {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.goods-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  color: #ff5000;
  font-size: 14px;
  font-weight: 500;
}

.goods-quantity {
  color: #666;
  font-size: 14px;
}

.goods-total {
  font-size: 16px;
  font-weight: bold;
  color: #ff5000;
  text-align: right;
  align-self: flex-start;
  margin-top: 8px;
}

/* 价格明细 */
.price-detail {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.price-item:last-child {
  margin-bottom: 0;
}

.price-label {
  color: #666;
}

.price-value {
  color: #333;
}

.price-value.discount {
  color: #52c41a;
}

.price-item.total {
  font-size: 16px;
  font-weight: bold;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.price-item.total .price-value {
  color: #ff5000;
}

/* 订单信息 */
.order-info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  font-size: 14px;
}

.info-label {
  color: #666;
  flex-shrink: 0;
  width: 80px;
}

.info-value {
  color: #333;
  text-align: right;
  flex: 1;
  word-break: break-all;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 60px; /* 底部导航栏高度 */
  left: 0;
  right: 0;
  background: white;
  padding: 12px 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.action-buttons .el-button {
  flex: 0 0 auto;
  min-width: 80px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .goods-item {
    flex-direction: column;
    gap: 8px;
  }

  .goods-image {
  width: 60px;
  height: 60px;
}

.goods-total {
  text-align: left;
  margin-top: 0;
}

.action-buttons {
  flex-wrap: wrap;
  justify-content: center;
}

.action-buttons .el-button {
    flex: 1 1 auto;
    min-width: 0;
  }
}

/* 状态颜色样式 */
.status-pending { color: #ff5000; }
.status-paid { color: #1890ff; }
.status-shipped { color: #52c41a; }
.status-received { color: #722ed1; }
.status-completed { color: #722ed1; }
.status-cancelled { color: #999; }
.status-refunded { color: #fa541c; }
</style>
